package com.htfyun;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

/**
 * Created by sst on 2018/1/29.
 */

public class MyTestView extends View {
    
    private String text = "Test";
    private Paint textPaint;
    public MyTestView(Context context) {
        super(context);
    }

    public MyTestView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MyTestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        drawText(canvas);
    }

    private void drawText(Canvas canvas) {
        
        if (textPaint == null) {
            textPaint = new Paint();
            textPaint.setTextSize(dipToPix(getContext(), 48));
            textPaint.setColor(Color.BLACK);
            textPaint.setAntiAlias(true);
            textPaint.setDither(true);
        }
        
        canvas.drawText(this.text, 100, 200, textPaint);
        
    }
    public void setText(String text) {
        this.text += text;
        invalidate();
    }
    
    public void clearText() {
        this.text = "";
        invalidate();
    }

    public static int dipToPix(Context context, int dip) {
        int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.getResources().getDisplayMetrics());
        return size;
    }
}
